<?php

namespace app\api\controller;

use app\admin\model\product\Attr;
use app\admin\model\product\Attrs;
use app\admin\model\product\Collect;
use app\admin\model\product\Lists;
use app\admin\model\product\Sku;
use app\admin\model\product\Value;
use app\common\controller\Api;
use think\Request;


class Productlists extends Api
{
    private static $model;
    protected $noNeedLogin = ['listsByField', 'read', 'sku'];
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Lists();
    }

    /**
     * 显示资源列表
     * @throws \think\exception\DbException
     */
    public function listsByField()
    {
        $pageSize = input('page_size', 15);

        $where = [
            'status' => 'normal',
        ];
        $categoryId = input('category_id');
        if ($categoryId) {
            $where['category_id'] = $categoryId;
        }

        $keyword = trim(input('keyword'));
        if ($keyword) {
            $where['name'] = ['like', '%' . $keyword . '%'];
        }

        $sid = trim(input('sid'));
        if ($sid) {
            $sinfo = \app\admin\model\Stores::find($sid);
            if (!$sinfo) {
                $this->error('该店铺不存在！');
            }

            if ($sinfo->status != 1) {
                $this->error('该店铺状态不正常！');
            }
            $where['sid'] = $sid;
        }

        $field = input('field');
        if ($field == 'is_recom') {
            $where['is_recom'] = 1;
        }

        $list = self::$model->field('id,name,image,sid,intro,goods_detail,original_price,member_price,sell_num,pics')->where($where)->order('sort asc')->paginate($pageSize)->each(function ($item) {
            $item['image'] = make_full_url($item['image']);
        });
        $this->success('商品列表', $list);
    }

    /**
     * 商品详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function read()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数缺失！');
        }

        $row = self::$model->field('id,name,sid,image,intro,goods_detail,original_price,member_price,sell_num,goods_num,pics')->find($id);
        if (!$row) {
            $this->error('该商品不存在！');
        }

        $row['image'] = make_full_url($row['image']);

        $pics = explode(',', $row['pics']);

        foreach ($pics as &$val) {
            $val = make_full_url($val);
        }

        $row['pics'] = $pics;

        $attrs = Attrs::where('product_id', $id)->select();
        $attrs_arr = [];
        if ($attrs) {
            foreach ($attrs as $v) {
                $name = Attr::where('id', $v['attr_id'])->value('name');
                $value_ids_arr = explode(',', $v['value_ids']);
                $sons = [];
                foreach ($value_ids_arr as $v1) {
                    $vname = Value::where('id', $v1)->value('name');
                    $sons[] = [
                        'id' => $v1,
                        'name' => $vname
                    ];
                }
                $item = [
                    'id' => $v['attr_id'],
                    'name' => $name,
                    'sons' => $sons
                ];
                $attrs_arr[] = $item;
            }
        }

        $row->attrs = $attrs_arr;
        $this->success('商品详情', $row);
    }

    /**
     * 商品的sku
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sku()
    {
        $product_id = $this->request->get('product_id');
        $attrs = $this->request->get('attrs');
        if (!$product_id || !$attrs) {
            $this->error('参数缺失！');
        }

        $attrs = json_encode(explode(',', $attrs));
        $pInfo = self::$model->find($product_id);
        if (!$pInfo) {
            $this->error('该商品不存在！');
        }

        $row = Sku::where('product_id', $product_id)->where('attrs', $attrs)
            ->find();
        if (!$row) {
            $this->error('该属性不存在！');
        }

        $this->success('商品属性', $row);
    }

    /**
     * 是否收藏商品
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function isCollect()
    {
        $product_id = $this->request->post('product_id');
        $id = $this->auth->id;
        $row = Collect::where('product_id', $product_id)->where('user_id', $id)->find();

        if ($row) {
            $this->success('已收藏该商品', true);
        } else {
            $this->success('未收藏该商品', false);
        }
    }

    /**
     * 收藏/取消
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeCollect()
    {
        $product_id = $this->request->post('product_id');
        $id = $this->auth->id;
        $row = Collect::where('product_id', $product_id)->where('user_id', $id)->find();
        if ($row) {
            Collect::where('id', $row->id)->delete();
            $this->success('取消成功');
        } else {
            Collect::create([
                'user_id' => $id,
                'product_id' => $product_id,
            ]);
            $this->success('收藏成功');
        }
    }
}
